<template>

  <!-- 搜索框 -->
  <el-card style="height: 80px">
    <el-form :model="queryForm" :inline="true" class="form">
      <el-form-item label="标题:">
        <el-input
            v-model="queryForm.queryTitle"
            placeholder="请输入标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="教练:" v-if="userStore.role===1">
        <el-input
            v-model="queryForm.queryTrainerName"
            placeholder="请输入教练名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select
            v-model="queryForm.queryState"
            placeholder="请选择状态"
            style="width: 100px"
            filterable
        >
          <el-option label="全部" :value="0"></el-option>
          <el-option label="待发布" :value="1"></el-option>
          <el-option label="已发布" :value="2"></el-option>
          <el-option label="已停止" :value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型:">
        <el-select
            v-model="queryForm.queryCourseType"
            placeholder="请选择"
            style="width: 200px"
            filterable
        >
          <el-option label="全部" :value="0"></el-option>
          <el-option
              v-for="item in courseTypeList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="search">
          搜索
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>


  <!-- 添加用户和批量删除 -->
  <el-card style="margin: 10px 0">
    <el-tooltip effect="dark" content="添加" placement="top">
      <el-button
          type="success"
          size="default"
          icon="Plus"
          @click="handleAdd"
      >
      </el-button>
    </el-tooltip>
    <!-- table展示用户信息 -->
    <el-table
        style="margin: 10px 0"
        border
        :data="coursesTableData"
    >
      <el-table-column
          label="教练"
          align="center"
          prop="trainerName"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="标题"
          align="center"
          prop="title"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="描述"
          align="center"
          prop="description"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="人数(MAX)"
          align="center"
          prop="maxParticipants"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="开始时间"
          align="center"
          prop="startTime"
          :formatter="formatDate"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="结束时间"
          align="center"
          prop="endTime"
          :formatter="formatDate"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="课程时长(小时/h)"
          align="center"
          prop="duration"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="地点"
          align="center"
          prop="location"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="价格"
          align="center"
          prop="price"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="类型"
          align="center"
          prop="categoryName"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="图片"
          align="center"
          prop="img"
      >
        <template #default="{ row }">
          <el-image style="width: 100px; height: 100px;" :preview-src-list="[row.img]" :src="row.img"
                    fit="cover"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="220px" align="center">
        <template #="{ row }">
          <el-tooltip effect="dark" content="发布" placement="top">
            <el-button
                type="success"
                size="small"
                icon="Sell"
                @click="handleEditState(row,2)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="停止" placement="top">
            <el-button
                type="warning"
                size="small"
                icon="SoldOut"
                @click="handleEditState(row,3)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="编辑" placement="top">
            <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="handleEdit(row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="handleDelete(row.courseId)"
            >
            </el-button>
          </el-tooltip>
        </template>

      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="findAll"
        @size-change="handler"
    />
  </el-card>

  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer" size="1000px">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{ coursesForm.courseId ? '更新' : '添加' }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="coursesForm" :rules="rules" ref="formRef">
        <el-form-item label="教练" prop="trainerId" v-if="userStore.role===1">
          <el-select
              placeholder="请选择教练"
              v-model="coursesForm.trainerId"
              filterable
          >
            <el-option
                v-for="item in trainerList"
                :key="item.trainerId"
                :label="item.name"
                :value="item.trainerId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="courseType">
          <el-select
              placeholder="请选择类型"
              v-model="coursesForm.courseType"
              filterable
          >
            <el-option
                v-for="item in courseTypeList"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="startTime">
          <el-col :span="10">
            <el-date-picker
                v-model="coursesForm.startTime"
                type="datetime"
                placeholder="开始时间"
            />
          </el-col>
          <el-col :span="2">至</el-col>
          <el-col :span="10">
            <el-date-picker
                v-model="coursesForm.endTime"
                type="datetime"
                placeholder="结束时间"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input
              placeholder="请您输入标题"
              v-model="coursesForm.title"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
              type="textarea"
              placeholder="请您输入描述"
              v-model="coursesForm.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="人数(MAX)" prop="maxParticipants">
          <el-input
              type="number"
              placeholder="请您输入最大人数"
              v-model="coursesForm.maxParticipants"
          ></el-input>
        </el-form-item>
        <el-form-item label="课程时长(小时/h)" prop="duration">
          <el-input
              :disabled="true"
              placeholder="请您输入课程时长"
              v-model="coursesForm.duration"
          ></el-input>
        </el-form-item>
        <el-form-item label="地点" prop="location">
          <el-input
              placeholder="请您输入地点"
              v-model="coursesForm.location"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input
              v-model="coursesForm.price"
              style="width: 240px"
              placeholder="请您输入价格"
              :formatter="(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
          />
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload
              class="upload-demo"
              :show-file-list="false"
              accept=".png,.jpg,.jpeg,.gif"
              drag
              :before-upload="handleBeforeUpload"
              :http-request="handleCustomUploadAvatar"
              multiple
          >
            <img style="width: 200px; height: 200px;" v-if="coursesForm.img"
                 :src="coursesForm.img" class="avatar" alt="图片"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>


</template>

<script setup lang="ts">
import {ref, reactive, onMounted, nextTick} from 'vue'
import {ElFormItem, ElMessage, ElMessageBox} from 'element-plus'
import {Plus} from "@element-plus/icons-vue";
import {apiGet, apiPost} from "@/utils/api.ts";
import {formatDate} from "@/utils/time.ts";
//获取用户相关
import {useUserStore} from '@/store/modules/user'

let userStore = useUserStore()
const localTime = new Date();
// 表单数据
let coursesForm = reactive(
    {
      courseId: 0,
      trainerId: 0,
      courseType: 0,
      title: '',
      description: '',
      maxParticipants: 50,
      duration: '',
      location: '',
      price: 0.00,
      img: '',
      startTime: localTime,
      endTime: localTime,
    })
//搜索表单数据
let queryForm = reactive({
  queryTitle: '',
  queryTrainerName: '',
  queryState: 0,
  queryCourseType: 0,
  trainerId: 0,
})

//默认页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(5)
//总个数
let total = ref<number>(0)
//存储全部用户的数组
let coursesTableData = ref([])
//存储全部教练的数组
let trainerList = ref<any>([])
//存储全部类型的数组
let courseTypeList = ref<any>([])
//定义响应式数据控制抽屉的显示与隐藏 添加用户和修改用户
let drawer = ref<boolean>(false)
//获取form组件实例
let formRef = ref<any>()
//获取全部用户信息
let findAll = async (pager = 1) => {
  //收集当前页码
  pageNo.value = pager
  let parameter = {
    page: pageNo.value,
    limit: pageSize.value,
    title: queryForm.queryTitle,
    trainerName: queryForm.queryTrainerName,
    state: queryForm.queryState,
    courseType: queryForm.queryCourseType,
    trainerId: userStore.role === 1 ? queryForm.trainerId : userStore.id
  }
  //获取表单数据
  let {data} = await apiGet('/courses/findAll', parameter)
  total.value = data.count
  coursesTableData.value = data.data
}

//查询所有教练信息
const findAllTrainer = async () => {
  let {data} = await apiGet('/trainers/findAllTrainers')
  trainerList.value = data
}
//查询所有类型信息
const findAllCourseType = async () => {
  let {data} = await apiGet('/courseCategories/findAllCategories')
  courseTypeList.value = data
}

//分页器下拉菜单的自定义事件的回调
const handler = () => {
  findAll()
}

//搜索按钮的回调
const search = () => {
  findAll()
}

//添加用户按钮的回调
const handleAdd = () => {
  //抽屉显示出来
  drawer.value = true
  //清空userParams的数据以及userParams继承User里面的所有数据
  Object.assign(coursesForm, {
    courseId: 0,
    trainerId: '',
    courseType: '',
    title: '',
    description: '',
    maxParticipants: 50,
    duration: '',
    location: '',
    price: 0.00,
    img: '',
    startTime: localTime,
    endTime: localTime,
  })
  coursesForm.duration = ((coursesForm.endTime.getTime() - coursesForm.startTime.getTime()) / (1000 * 60 * 60)).toFixed(2).toString()
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

//更新用户按钮的回调
const handleEdit = (row: any) => {
  //抽屉显示出来
  drawer.value = true
  //将用户的信息赋值给userParams
  Object.assign(coursesForm, {
    ...row
  })
  coursesForm.startTime = new Date(coursesForm.startTime);
  coursesForm.endTime = new Date(coursesForm.endTime);
  coursesForm.duration = ((coursesForm.endTime.getTime() - coursesForm.startTime.getTime()) / (1000 * 60 * 60)).toFixed(2).toString()
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

//保存按钮的回调
const save = async () => {
  coursesForm.trainerId = userStore.role === 1 ? coursesForm.trainerId : userStore.id
  if (!coursesForm.trainerId || !coursesForm.courseType) {
    ElMessage.error('请选择教练和课程类型')
    return
  }
  coursesForm.duration = (coursesForm.endTime.getTime() - coursesForm.startTime.getTime()).toString()
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate()
  //保存按钮:添加新的用户|更新已有的用户账号信息
  coursesForm.courseId ? await apiPost('/courses/edit', {...coursesForm}) : await apiPost('/courses/add', {...coursesForm})
  await findAll()
  drawer.value = false
}

//发布按钮和停止按钮
const handleEditState = async (row: any, type: number) => {
  ElMessageBox.confirm('此操作将改变课程状态, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        await apiPost('/courses/editState', {courseId: row.courseId, state: type})
        await findAll()
      })
      .catch(() => {
      })
}

//删除
const handleDelete = async (courseId: number) => {
  //提示用户确认删除吗
  ElMessageBox.confirm('此操作将永久删除该课程, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        await apiPost('/courses/delete', {courseId})
        await findAll(coursesTableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
      })
      .catch(() => {
      })
}

//上传文件之前做的一些判断
const handleBeforeUpload = (file) => {
  // 检查文件类型 只能上传.png,.jpg,.jpeg,.gif
  const isExcel = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif';
  if (!isExcel) {
    ElMessage.error('上传文件只能是.png,.jpg,.jpeg,.gif 格式!');
    return false;
  }

  //上传文件大小不能超过20M
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    ElMessage.error('上传文件大小不能超过 20MB!');
    return false;
  }
  return isExcel && isLt20M;
};
const handleCustomUploadAvatar = async (option) => {
  const formData = new FormData();
  formData.append('file', option.file);
  let {msg} = await apiPost('/upload/img', formData, {headers: {'Content-Type': 'multipart/form-data'}});
  coursesForm.img = msg;
};
const validatorTitle = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入课程标题'));
  } else {
    callback();
  }
}
const validatorCourseType = (rule: any, value: number, callback: any) => {
  if (!value) {
    callback(new Error('请选择课程类型'));
  } else {
    callback();
  }
}
const validatorTrainerId = (rule: any, value: number, callback: any) => {
  if (!value) {
    callback(new Error('请选择教练'));
  } else {
    callback();
  }
}
const validatorDescription = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入课程描述'));
  } else {
    callback();
  }
}
const validatorMaxParticipants = (rule: any, value: number, callback: any) => {
  if (value <= 0) {
    callback(new Error('请输入最大人数'));
  } else {
    callback();
  }
}

const validatorLocation = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入课程地点'));
  } else {
    callback();
  }
}

const validatorPrice = (rule: any, value: number, callback: any) => {
  if (value < 0) {
    callback(new Error('请输入正确的价格'));
  } else {
    callback();
  }
}

const validatorImg = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请上传图片'));
  } else {
    callback();
  }
}

const validatorSelectTime = (rule: any, value: any, callback: any) => {
  coursesForm.duration = ((coursesForm.endTime.getTime() - coursesForm.startTime.getTime()) / (1000 * 60 * 60)).toFixed(2).toString()
  if (!coursesForm.startTime || !coursesForm.endTime) {
    callback(new Error('请选择课程时间段'));
  } else {
    //判断开始时间不能大于结束时间
    if (coursesForm.startTime > coursesForm.endTime) {
      callback(new Error('开始时间不能大于结束时间'));
    }
    //判断开始时间不能小于现在时间
    if (coursesForm.startTime <= localTime) {
      callback(new Error('开始时间不能小于现在时间'));
    }
    callback();
  }
}

//表单校验的规则对象
const rules = {
  title: [{required: true, trigger: 'blur', validator: validatorTitle}],
  courseType: [{required: true, trigger: ['blur', 'change'], validator: validatorCourseType}],
  trainerId: [{required: true, trigger: ['blur', 'change'], validator: validatorTrainerId}],
  description: [{required: true, trigger: 'blur', validator: validatorDescription}],
  maxParticipants: [{required: true, trigger: 'blur', validator: validatorMaxParticipants}],
  location: [{required: true, trigger: 'blur', validator: validatorLocation}],
  price: [{required: true, trigger: 'blur', validator: validatorPrice}],
  img: [{required: true, trigger: 'blur', validator: validatorImg}],
  startTime: [{required: true, trigger: ['blur', 'change'], validator: validatorSelectTime}],
}
//组件挂载完毕
onMounted(() => {
  findAll()
  findAllTrainer()
  findAllCourseType()
})
</script>

<style scoped>
</style>
